<?php
if( !defined('IN_INDEX') )
{
	printError("ACCESS DENIED", "This page is hidden.");
	exit;
}
if(!checkSession())
{
			function redirect($url)
			{
			?>
				<script type="text/javascript">
					{
					window.location = "<?=$url?>";
					}
				</script>
			<?php 
			}
			redirect("index.php?action=login");
	exit;
}
include('inc/functions_blog.php');
include('inc/functions_gym.php');

$time_now = time();
$rpeactivated = $USER->getActivateRpe();

$blog['title'] = "";
$blog['exercise'] = array();
$blog['comment'] = "";
$blog['bodyweight'] = calcFromKg($USER->getBodyweight());
$blog['place'] = $USER->getPlace();
$blog['hour'] = 1;
$blog['minute'] = 0;
$blog['day'] = date('d', $time_now);
$blog['month'] = date('m', $time_now);
$blog['year'] = date('Y', $time_now);
$blog['meet'] = 0;
$blog['category'] = $USER->getCategory();
$disable_comments = 0;

$missing = array();
$output ="";
// RPE Avtivated
if($rpeactivated == 1)
{
if(isset($_POST['blog_submit']))
{
	
	
	$blog_checked = 0;
	
	$blog['title']=str_replace("'", "", $_POST['title']);
	$blog['comment']=str_replace("'", "", $_POST['comment']);
	$blog['bodyweight']=$_POST['bodyweight'];
	$blog['hour']=$_POST['timespent_hours'];
	$blog['minute']=$_POST['timespent_minutes'];
	$blog['place']=$_POST['place'];
	$blog['gym_id'] = $BLOG['gym_id'];
	$blog['day']=$_POST['day'];
	$blog['month']=$_POST['month'];
	$blog['year']=$_POST['year'];
	$blog['meet']=$_POST['meet'];
	$blog['category']=$_POST['category'];
	
	if(isset($_POST['blog_disablecomments']) && $_POST['blog_disablecomments'] == "on")
	{
		$disable_comments = 1;
	}
	if($blog['meet'] != 2)
	{
		if(isset($_POST['kgs']) && isset($_POST['reps']) && isset($_POST['rpe']) && isset($_POST['url']) && isset($_POST['type']) && isset($_POST['type_nr']))
		{
			$kglist = $_POST['kgs'];
			$replist = $_POST['reps'];
			$rpelist = $_POST['rpe'];
			$urllist = $_POST['url'];
			$typelist = $_POST['type'];
			$typenrlist = $_POST['type_nr'];
			
			foreach($kglist as $key => $value)
			{
				$exercise_id = $key;
				$exercise_set = array();
				foreach($value as $k => $v)
				{
					$exercise_kg = str_replace(',', '.', $v);
					$exercise_rep = $replist[$key][$k];
					$exercise_rpe = $rpelist[$key][$k];
					$exercise_url = $urllist[$key][$k];
					$exercise_type = $typelist[$key][$k];
					$exercise_type_nr = $typenrlist[$key][$k];
					
					if($exercise_kg != '' || $exercise_rep != '' || $exercise_rpe != '' || $exercise_url != '' || $exercise_type != '' || $exercise_type_nr != '')
					{
						$exercise_set[] = array('kg' => $exercise_kg, 'rep' => $exercise_rep, 'rpe' => $exercise_rpe, 'url' => $exercise_url, 'type' => $exercise_type, 'type_nr' => $exercise_type_nr);
					}
				}
				$blog['exercise'][] = array('id' => $exercise_id, 'set' => $exercise_set);
			}
		}
		
		foreach($blog as $k => $v)
		{
			// echo $k . " | " . $v . "<br />\n";
			if(isset($v) && $v != "")
			{
				if($k == "exercise")
				{
					if(count($v) > 0)
					{
						$blog_checked++;
					}
					else
					{
						$missing['exercise'] = 'no_exercise';
					}
				}
				else
				{
					$blog_checked++;
				}
			}
			else
			{
				$missing[$k] = "missing";
			}
		}
	}
	else
	{
		foreach($blog as $k => $v)
		{
			if(isset($v) && $v != "")
			{
				$blog_checked++;
			}
			else
			{
				$missing[$k] = "missing";
			}
		}
	}
	if($blog_checked >= 12 || ($blog['meet'] == 2 && $blog_checked >= 12))
	{
		$time_then = mktime(date('H', $time_now), date('i', $time_now), date('s', $time_now), $blog['month'], $blog['day'], $blog['year']);
		$body_weight = str_replace(',', '.', $blog['bodyweight']);
		$place = $blog['place'];
		$category = $blog['category'];
		
		// Add training to DB
		$sql = "INSERT INTO " . TRAINING_TABLE . " SET ".
		"user_id='" . $USER->getId() . "', ".
		"title='" . $blog['title'] . "', ".
		"date='" . $time_then . "', ".
		"comment='" .  $blog['comment'] . "', ".
		"place='" .  $blog['place'] . "', ".
		"bodyweight='" .  calcToKg($body_weight) . "', ".
		"timespent_hours='" .  $blog['hour'] . "', ".
		"timespent_minutes='" .  $blog['minute'] . "', ".
		"disable_comment='" . $disable_comments . "', ".
		"meet='" .  $blog['meet'] . "', ".
		"gym_id='" . update_gym( $blog['gym_id'], $blog['place']) . "', ".
		"category='" . $blog['category'] . "'";
		if(!$result = $db->sql_query($sql))
		{
			printError("SQL ERROR", mysql_error($sql));
		}
		else
		{
			$id = mysql_insert_id();
			
			foreach($blog['exercise'] as $key => $value)
			{
				foreach($value['set'] as $k => $v)
				{
					// Add lifts to DB
					$sql2 = "INSERT INTO " . LIFT_TABLE . " SET ".
					"training_id='" . $id . "', ".
					"exercise_id='" . $value['id'] . "', ".
					"kg='" . calcToKg($v['kg']) . "', ".
					"rep='" . $v['rep'] . "', ". 
					"rpe='" . $v['rpe'] . "', ". 
					"url='" . $v['url'] . "', ".
					"type='" . $v['type'] . "', ".
					"type_nr='" . $v['type_nr'] . "'";
					
					if(!$result2 = $db->sql_query($sql2))
					{
						printError("SQL ERROR", mysql_error($sql2));
					}
				}
			}
		}
			// Add +1 to user_posts and updates bodyweight, place and category
			$sql3 = "UPDATE users SET user_posts = user_posts+1, user_bodyweight = " .  calcToKg($body_weight) . ", user_place='". $place ."', user_category='". $category ."'  WHERE user_id =" . $USER->getId() . "";
			if(!$result3 = $db->sql_query($sql3))
			{
				printError("SQL ERROR", mysql_error($sql3));
			}
			
			// Delete set with 0x0
			$sql4 = "DELETE FROM ". LIFT_TABLE ." WHERE kg=0 AND rep=0";
			if(!$result4 = $db->sql_query($sql4))
			{
				printError("SQL ERROR", mysql_error($sql4));
			}
			
			echo"<br /><br /><br /><br /><br /><br /><br /><br /><br />
			<center><meta http-equiv=\"refresh\"content=\"2;url=index.php?action=profile&sub=show&tid=$id\">";
			if($blog['meet'] == 0)
			{
				echo "<h1>" . ucfirst(translate('postsubmited')) . "</h1>";
			}
			elseif($blog['meet'] == 1 || $blog['meet'] == 3)
			{
				echo "<h1>" . ucfirst(translate('postsubmitedmeet')) . "</h1>";
			}
			elseif($blog['meet'] == 2)
			{
				echo "<h1>" . ucfirst(translate('postsubmitedtext')) . "</h1>";
			}
			echo "<br/>" . translate('redirectedin') . " <a href=\"index.php?action=profile&sub=show&tid=$id\">" . translate('clickhere') . "</a></center>
			<div class='fixed'>
					</div>
				</div>
				</div>
			<div class='fixed'>
			</div>
			<div id='footer'>
			<a id='gotop' href='#' onclick='MGJS.goTop();return false;'>" . translate('top') . "</a>
				<div align='center' id='copyright'>&copy; " . translate('copyrightyear') . " " . translate('header_text'). " - " .  translate('curversion') ." - <a href='index.php?action=contact'>" . translate('contact') ."</a> - <a href='index.php?action=about'>" . translate('about') . "</a> - " . translate('onlineusers'). ": " . getActiveUsers() . "<br />
                </div>";
			exit;

		}
	}
	
	//Preview
	echo "<h3>" . translate('preview'). "</h3><br />";
	foreach($blog['exercise'] as $key => $value)
	{
		echo "<b>" . translate(getExercisename($value['id'])) . "</b><br />\n";
		foreach($value['set'] as $k => $v)
		{
			echo "    " . r_nr2(calcFromKg($v['kg'])) . $w_metric . " x " . $v['rep'] . "<br />\n";
		}
		echo "<br />\n";
	} 
	
}
// RPE Deactivated
else
{
	if(isset($_POST['blog_submit']))
{
	
	
	$blog_checked = 0;
	
	$blog['title']=str_replace("'", "", $_POST['title']);
	$blog['comment']=str_replace("'", "", $_POST['comment']);
	$blog['bodyweight']=$_POST['bodyweight'];
	$blog['hour']=$_POST['timespent_hours'];
	$blog['minute']=$_POST['timespent_minutes'];
	$blog['place']=$_POST['place'];
	$blog['gym_id']=$_POST['gym_id'];
	$blog['day']=$_POST['day'];
	$blog['month']=$_POST['month'];
	$blog['year']=$_POST['year'];
	$blog['meet']=$_POST['meet'];
	$blog['category']=$_POST['category'];
	
	if(isset($_POST['blog_disablecomments']) && $_POST['blog_disablecomments'] == "on")
	{
		$disable_comments = 1;
	}
	if($blog['meet'] != 2)
	{
		if(isset($_POST['kgs']) && isset($_POST['reps']) && isset($_POST['url']) && isset($_POST['type']) && isset($_POST['type_nr']))
		{
			$kglist = $_POST['kgs'];
			$replist = $_POST['reps'];
			$urllist = $_POST['url'];
			$typelist = $_POST['type'];
			$typenrlist = $_POST['type_nr'];
			
			foreach($kglist as $key => $value)
			{
				$exercise_id = $key;
				$exercise_set = array();
				foreach($value as $k => $v)
				{
					$exercise_kg = str_replace(',', '.', $v);
					$exercise_rep = $replist[$key][$k];
					$exercise_url = $urllist[$key][$k];
					$exercise_type = $typelist[$key][$k];
					$exercise_type_nr = $typenrlist[$key][$k];
					
					if($exercise_kg != '' || $exercise_rep != '' || $exercise_url != '' || $exercise_type != '' || $exercise_type_nr != '')
					{
						$exercise_set[] = array('kg' => $exercise_kg, 'rep' => $exercise_rep, 'url' => $exercise_url, 'type' => $exercise_type, 'type_nr' => $exercise_type_nr);
					}
				}
				$blog['exercise'][] = array('id' => $exercise_id, 'set' => $exercise_set);
			}
		}
		
		foreach($blog as $k => $v)
		{
			// echo $k . " | " . $v . "<br />\n";
			if(isset($v) && $v != "")
			{
				if($k == "exercise")
				{
					if(count($v) > 0)
					{
						$blog_checked++;
					}
					else
					{
						$missing['exercise'] = 'no_exercise';
					}
				}
				else
				{
					$blog_checked++;
				}
			}
			else
			{
				$missing[$k] = "missing";
			}
		}
	}
	else
	{
		foreach($blog as $k => $v)
		{
			if(isset($v) && $v != "")
			{
				$blog_checked++;
			}
			else
			{
				$missing[$k] = "missing";
			}
		}
	}
	if($blog_checked >= 12 || ($blog['meet'] == 2 && $blog_checked >= 12))
	{
		$time_then = mktime(date('H', $time_now), date('i', $time_now), date('s', $time_now), $blog['month'], $blog['day'], $blog['year']);
		$body_weight = str_replace(',', '.', $blog['bodyweight']);
		$place = $blog['place'];
		$category = $blog['category'];
		
		// Add training to DB
		$sql = "INSERT INTO " . TRAINING_TABLE . " SET ".
		"user_id='" . $USER->getId() . "', ".
		"title='" . $blog['title'] . "', ".
		"date='" . $time_then . "', ".
		"comment='" .  $blog['comment'] . "', ".
		"place='" .  $blog['place'] . "', ".
		"bodyweight='" .  calcToKg($body_weight) . "', ".
		"timespent_hours='" .  $blog['hour'] . "', ".
		"timespent_minutes='" .  $blog['minute'] . "', ".
		"disable_comment='" . $disable_comments . "', ".
		"meet='" .  $blog['meet'] . "', ".
		"gym_id='" .intval( update_gym( $blog['gym_id'], $blog['place'] ) ). "', ".
		"category='" . $blog['category'] . "'";
		if(!$result = $db->sql_query($sql))
		{
			printError("SQL ERROR", mysql_error($sql));
		}
		else
		{
			$id = mysql_insert_id();
			
			foreach($blog['exercise'] as $key => $value)
			{
				foreach($value['set'] as $k => $v)
				{
					// Add lifts to DB
					$sql2 = "INSERT INTO " . LIFT_TABLE . " SET ".
					"training_id='" . $id . "', ".
					"exercise_id='" . $value['id'] . "', ".
					"kg='" . calcToKg($v['kg']) . "', ".
					"rep='" . $v['rep'] . "', ". 
					"url='" . $v['url'] . "', ".
					"type='" . $v['type'] . "', ".
					"type_nr='" . $v['type_nr'] . "'";
					
					if(!$result2 = $db->sql_query($sql2))
					{
						printError("SQL ERROR", mysql_error($sql2));
					}
				}
			}
		}
			// Add +1 to user_posts and updates bodyweight, place and category
			$sql3 = "UPDATE users SET user_posts = user_posts+1, user_bodyweight = " .  calcToKg($body_weight) . ", user_place='". $place ."', user_category='". $category ."'  WHERE user_id =" . $USER->getId() . "";
			if(!$result3 = $db->sql_query($sql3))
			{
				printError("SQL ERROR", mysql_error($sql3));
			}
			
			// Delete set with 0x0
			$sql4 = "DELETE FROM ". LIFT_TABLE ." WHERE kg=0 AND rep=0";
			if(!$result4 = $db->sql_query($sql4))
			{
				printError("SQL ERROR", mysql_error($sql4));
			}
			
			echo"<br /><br /><br /><br /><br /><br /><br /><br /><br />
			<center><meta http-equiv=\"refresh\"content=\"2;url=index.php?action=profile&sub=show&tid=$id\">";
			if($blog['meet'] == 0)
			{
				echo "<h1>" . ucfirst(translate('postsubmited')) . "</h1>";
			}
			elseif($blog['meet'] == 1 || $blog['meet'] == 3)
			{
				echo "<h1>" . ucfirst(translate('postsubmitedmeet')) . "</h1>";
			}
			elseif($blog['meet'] == 2)
			{
				echo "<h1>" . ucfirst(translate('postsubmitedtext')) . "</h1>";
			}
			echo "<br/>" . translate('redirectedin') . " <a href=\"index.php?action=profile&sub=show&tid=$id\">" . translate('clickhere') . "</a></center>
			<div class='fixed'>
					</div>
				</div>
				</div>
			<div class='fixed'>
			</div>
			<div id='footer'>
			<a id='gotop' href='#' onclick='MGJS.goTop();return false;'>" . translate('top') . "</a>
				<div align='center' id='copyright'>&copy; " . translate('copyrightyear') . " " . translate('header_text'). " - " .  translate('curversion') ." - <a href='index.php?action=contact'>" . translate('contact') ."</a> - <a href='index.php?action=about'>" . translate('about') . "</a> - " . translate('onlineusers'). ": " . getActiveUsers() . "<br />
                </div>";
			exit;

		}
	}
	
	//Preview
	echo "<h3>" . translate('preview'). "</h3><br />";
	foreach($blog['exercise'] as $key => $value)
	{
		echo "<b>" . translate(getExercisename($value['id'])) . "</b><br />\n";
		foreach($value['set'] as $k => $v)
		{
			echo "    " . r_nr2(calcFromKg($v['kg'])) . $w_metric . " x " . $v['rep'] . "<br />\n";
		}
		echo "<br />\n";
	} 
}
$array_meet = array(2 => "text", 3 => "meetiwf", 1 => "meetipf", 0 => "trainingt");

$array_set = array('superset' => "superset", 'dropset' => "dropset");

$array_rpe = array(1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5", 6 => "6", 7 => "7", 8 => "8", 9 => "9", 10 => "10");

$array_set_nr = array(1 => "Nr.1", 2 => "Nr.2", 3 => "Nr.3", 4 => "Nr.4", 5 => "Nr.5", 6 => "Nr.6", 7 => "Nr.7", 8 => "Nr.8", 9 => "Nr.9", 10 => "Nr.10", 11 => "Nr.11", 12 => "Nr.12", 13 => "Nr.13", 14 => "Nr.14", 15 => "Nr.15", 16 => "Nr.16", 17 => "Nr.17", 18 => "Nr.18", 19 => "Nr.19", 20 => "Nr.20");

$array_cat = getTrainingCat($USER->getId());

$rpeactivated = $USER->getActivateRpe();

?>
<!--
<script src="./jscript/prettyphoto/js/jquery-1.4.4.min.js" type="text/javascript" charset="utf-8"></script>

<link rel="stylesheet" href="./jscript/prettyphoto/css/prettyPhoto.css" type="text/css" media="screen" charset="utf-8" />
<script src="./jscript/prettyphoto/js/jquery.prettyPhoto.js" type="text/javascript" charset="utf-8"></script>
-->
<script type="text/javascript" src="./jscript/autocomplete/jquery.autocomplete.js"></script>
<link type="text/css" rel="stylesheet" href="./jscript/autocomplete/autocomplete.css" /> 

<noscript>
<center>
<span style="color:red;"><h2><?php echo translate('javawarning'); ?></h2></span></p><br  />
</center>
</noscript>

<script type="text/javascript">
// Dropdown boxes
function updateOptions(chosen, nameofbox)
{
	var selbox = document.getElementById(nameofbox);
	selbox.options.length = 0;
	 
	if (chosen == " ") 
	{
		selbox.options[selbox.options.length] = new Option('<?php echo translate("selectcategoryfirst"); ?>',' ');
 	}
 	
<?php
foreach($EXERCISE_LIST as $key => $value)
{
	$ex_id = $value['id'];
	$ex_list = $value['list'];
	$output = translate($value['name']);
	echo "if(chosen == \"" . $key . "\") {\n";
	foreach($ex_list as $k => $v)
	{
		$output = translate($v['name']);
		echo "	selbox.options[selbox.options.length] = new Option('" . $output . "', '" . $v['id'] . "');\n";
	}
	echo "}\n";
}
?>
}

	function add_video(id)
	{
		var el = document.getElementById('add_video_' + id);
		var b = document.getElementById('add_video_button_' + id);
		
		if(el.style.display == "block")
		{
			el.style.display="none";
			b.innerHTML = '<img src="img/video_link.png" />';
		}
		else
		{
			el.style.display="block";
			b.innerHTML = '<img src="img/video_link.png" />';
		}
	}
	
	function edit_set(id)
	{
		var el = document.getElementById('edit_set_' + id);
		var b = document.getElementById('edit_set_button_' + id);
		
		if(el.style.display == "block")
		{
			el.style.display="none";
			b.innerHTML = '<img src="img/book_edit.png" />';
		}
		else
		{
			el.style.display="block";
			b.innerHTML = '<img src="img/book_edit.png" />';
		}
	}
	
	// Add exercise
	<?php
	echo "var exercise_count = " . count($blog['exercise']) . ";
	var countset = new Array();";
	foreach($blog['exercise'] as $key => $value)
	{
		$counter = count($value['set']);
		echo "countset[" . ($key+1) . "] = " . $counter . ";\n
		";
	} ?>
	var exerciselist = new Array();
	
	function add_exercise() {
		var element = document.getElementById('exercise_list');
		if( $('#mod_display').val() == 'slb'){
			 var i = document.new_ex_form.select_exercise1.selectedIndex;
			 var selected_text = document.new_ex_form.select_exercise1.options[i].text;
			 var selected_value = document.new_ex_form.select_exercise1.options[i].value;
		}else{
			var selected_text = document.new_ex_form.select_exercise2.value;
			var selected_value = document.new_ex_form.select_exercise.value;
		}
		
		if(selected_value == '0'){
			//selected_text = $("#select_exercise1").val();
			selected_text = $('#select_exercise1 option:selected').text();
			selected_value = $("#select_exercise1").val();
		}
		
		if(selected_value != '')
		{
			exercise_count += 1;
			countset[exercise_count] = 0;
			var newdiv = document.createElement('div');
			var divIdName = 'exercise[' + exercise_count + ']';
			newdiv.setAttribute('id',divIdName);
		
			newdiv.innerHTML += '<a name="exercise_' + exercise_count + '" /></a><br /><span style="font-weight:bold; font-size:16px;">' + selected_text + '</span> <a href="javascript:void(0);" title="<?php echo translate('removeexercise'); ?>" onclick="remove_exercise(' + exercise_count + '); return false;"><?php echo '<img src="img/decline.png" />'; ?></a>'+
				'<a href="javascript:void(0);" title="<?php echo translate('editexercise'); ?>" onclick="edit_exercise(' + exercise_count + ','+selected_value+'); return false;"><img src="img/book_edit.png" /></a>'+
				'<a href="javascript:void(0);" title="<?php echo translate('sortexercise'); ?>" onclick="sort_exercise(); return false;"><img src="img/arrow_switch.png" /></a><br />' 
				+ '<a href="javascript:void(0);" onclick="add_set(' + exercise_count + ', ' + selected_value + '); return false;"><div style="float: left; clear: right; padding-right: 5px;"><img src="img/add.png" /></div> <?php echo translate('addnewsettoexercise'); ?></a><div style="clear: both;"></div>';
			element.appendChild(newdiv);
			add_set(exercise_count, selected_value);
			
			
			var anchorRef='exercise_' + exercise_count;
			var loc = document.location + '';
			loc = loc.substring(loc.length - 1, loc.length);
			
			if(loc == '#')
			{
				document.location=document.location + anchorRef;
			}
			else
			{
				var url = document.location + '';
				if(url.indexOf('#') != -1)
				{
					document.location=url.substring(0, url.indexOf('#')) + "#" + anchorRef;
				}
				else
				{
					document.location=document.location + "#" + anchorRef;
				}
			}
			
		}
	}

	// ADD SET
	function add_set(c, id)
	{
		countset[c] += 1;
		var el = document.getElementById('exercise[' + c + ']');
		var newdiv = document.createElement('div');
  		var divIdName = 'set['+ countset[c] +'][' + c + ']';
  		newdiv.setAttribute('id',divIdName);
		
		if(countset[c] <= 1)
		{
	insertText = '<strong><?php echo ucf(translate('set')) . " " . translate('nr'); ?> ' + countset[c] + '</strong><br />'
	+ '<input onkeyup="isNumber(this)" id="kg_' + countset[c] + '" name="kgs[' + id + '][]' + '" size="4" type="text" /><b><?php echo translate($w_metric); ?></b> ' 
	+ '<input onkeyup="isNumber2(this)" id="rep_' + countset[c] + '" name="reps[' + id + '][]' + '" size="2" type="text" /><b><?php echo ucf(translate('reps')); ?></b> '
	<?php if($rpeactivated == 1)
	{
	?>
	+ '<select id="rpe_' + countset[c] + '" name="rpe[' + id + '][]' + '"><option value="" selected="selected"></option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option></select><b><?php echo translate('RPE'); ?></b> <a href="./img/rpe.JPG" rel="prettyPhoto" title="<?php echo translate('clicktoopeninanewpage'); ?>" target="_blank">[?]</a> '
	<?php
	}
	?>
	+ '<a href="javascript:void(0);" title="<?php echo translate("add_video"); ?>" onclick="add_video(' + countset[c] + '' + id + '); return false;"><span id="add_video_button_' + countset[c] + '"><?php echo '<img src="img/video_add.png" />'; ?></span></a> '				
	+ '<a href="javascript:void(0);" title="<?php echo translate("edit_set"); ?>" onclick="edit_set(' + countset[c] + '' + id + '); return false;"><span id="edit_set_button_' + countset[c] + '"><?php echo '<img src="img/book_edit.png" />'; ?></span></a>'
	+ '<div class="ex_stats" id="add_video_' + countset[c] + '' + id + '"><br /><input id="url_' + countset[c] + '" name="url[' + id + '][]' + '" size="40" type="text" /><b><?php echo ucf(translate('url')); ?></b><br /><br /></div>'
	+ '<div class="ex_stats" id="edit_set_' + countset[c] + '' + id + '"><br /><select id="type_' + countset[c] + '" name="type[' + id + '][]' + '"><option value="" selected="selected"><?php echo ucf(translate('selecttype')); ?></option><option value="superset"><?php echo ucf(translate('superset')); ?></option><option value="dropset"><?php echo ucf(translate('dropset')); ?></option></select><select id="type_nr_' + countset[c] + '" name="type_nr[' + id + '][]' + '"><option value="" selected="selected"><?php echo ucf(translate('selecttypenr')); ?></option><option value="1">Nr.1</option><option value="2">Nr.2</option><option value="3">Nr.3</option><option value="4">Nr.4</option><option value="5">Nr.5</option><option value="6">Nr.6</option><option value="7">Nr.7</option><option value="8">Nr.8</option><option value="9">Nr.9</option><option value="10">Nr.10</option><option value="11">Nr.11</option><option value="12">Nr.12</option><option value="13">Nr.13</option><option value="14">Nr.14</option><option value="15">Nr.15</option><option value="16">Nr.16</option><option value="17">Nr.17</option><option value="18">Nr.18</option><option value="19">Nr.19</option><option value="20">Nr.20</option></select><br /><br /></div>';
		}
		else
		{
	insertText = '<strong><?php echo ucf(translate('set')) . " " . translate('nr'); ?> ' + countset[c] + '</strong><br />'
	+ '<input onkeyup="isNumber(this)" id="kg_' + countset[c] + '" name="kgs[' + id + '][]' + '" size="4" type="text" /><b><?php echo translate($w_metric); ?></b> ' 
	+ '<input onkeyup="isNumber2(this)" id="rep_' + countset[c] + '" name="reps[' + id + '][]' + '" size="2" type="text" /><b><?php echo ucf(translate('reps')); ?></b> '
	<?php if($rpeactivated == 1)
	{
	?>
	+ '<select id="rpe_' + countset[c] + '" name="rpe[' + id + '][]' + '"><option value="" selected="selected"></option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option></select><b><?php echo translate('RPE'); ?></b> <a href="./img/rpe.JPG" rel="prettyPhoto" title="<?php echo translate('clicktoopeninanewpage'); ?>" target="_blank">[?]</a> '
	<?php
	}
	?>
	+ '<a href="javascript:void(0);" title="<?php echo translate('removeset'); ?>" onclick="remove_set(' + countset[c] + ', ' + c + '); return false;"> <?php echo '<img src="img/decline.png" />'; ?></a> '
	+ '<a href="javascript:void(0);" title="<?php echo translate("add_video"); ?>" onclick="add_video(' + countset[c] + '' + id + '); return false;"><span id="add_video_button_' + countset[c] + '"><?php echo '<img src="img/video_add.png" />'; ?></span></a> '				
	+ '<a href="javascript:void(0);" title="<?php echo translate("edit_set"); ?>" onclick="edit_set(' + countset[c] + '' + id + '); return false;"><span id="edit_set_button_' + countset[c] + '"><?php echo '<img src="img/book_edit.png" />'; ?></span></a>'
	+ '<div class="ex_stats" id="add_video_' + countset[c] + '' + id + '"><br /><input id="url_' + countset[c] + '" name="url[' + id + '][]' + '" size="40" type="text" /><b><?php echo ucf(translate('url')); ?></b><br /><br /></div>'
	+ '<div class="ex_stats" id="edit_set_' + countset[c] + '' + id + '"><br /><select id="type_' + countset[c] + '" name="type[' + id + '][]' + '"><option value="" selected="selected"><?php echo ucf(translate('selecttype')); ?></option><option value="superset"><?php echo ucf(translate('superset')); ?></option><option value="dropset"><?php echo ucf(translate('dropset')); ?></option></select><select id="type_nr_' + countset[c] + '" name="type_nr[' + id + '][]' + '"><option value="" selected="selected"><?php echo ucf(translate('selecttypenr')); ?></option><option value="1">Nr.1</option><option value="2">Nr.2</option><option value="3">Nr.3</option><option value="4">Nr.4</option><option value="5">Nr.5</option><option value="6">Nr.6</option><option value="7">Nr.7</option><option value="8">Nr.8</option><option value="9">Nr.9</option><option value="10">Nr.10</option><option value="11">Nr.11</option><option value="12">Nr.12</option><option value="13">Nr.13</option><option value="14">Nr.14</option><option value="15">Nr.15</option><option value="16">Nr.16</option><option value="17">Nr.17</option><option value="18">Nr.18</option><option value="19">Nr.19</option><option value="20">Nr.20</option></select><br /><br /></div>';	
		}
		newdiv.innerHTML = insertText;
		el.appendChild(newdiv);
	}

	function remove_exercise(exercise)
	{
		var el = document.getElementById('exercise[' + exercise + ']');
		var main = document.getElementById('exercise_list');
		main.removeChild(el);
	}
	
	function remove_set(set, exercise)
	{
		var el = document.getElementById('set[' + set + '][' + exercise + ']');
		var main = document.getElementById('exercise[' + exercise + ']');
		main.removeChild(el);
	}

</script>

<!-- TinyMCE -->
<!--
<script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
-->
<script type="text/javascript">
tinyMCE.init({
        // General options
		language : "<?php if($USER->getLang() == 'no')
		{
			echo "no";
		}
		elseif($USER->getLang() == 'en')
		{
		 echo "en";	
		}
		else
		{
			echo "en";	
		}
		?>",
        mode : "textareas",
        theme : "advanced",
        plugins : "spellchecker,pagebreak,style,layer,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager",

        // Theme options
        theme_advanced_buttons1 : "save,newdocument,|,undo,redo,|,cut,copy,paste,pastetext,pasteword,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect|,forecolor,backcolor,|,charmap,emotions,iespell,media,advhr,|,image,insertimage",
		
        theme_advanced_buttons2 : "search,replace,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,cleanup,code,|,insertdate,inserttime,preview,|,hr,removeformat,visualaid,|,sub,sup,|,print,|,fullscreen,|,insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak",
		
		theme_advanced_buttons3 : "",
		
        theme_advanced_buttons4 : "",
		
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Skin options
        skin : "o2k7",
        skin_variant : "silver",
});
</script>
<!-- /TinyMCE -->

<script language="JavaScript" type="text/javascript">
function isNumber(field) {
var re = /^[0-9-'.'-',']*$/;
if (!re.test(field.value)) {
alert('<?php echo translate('numericwarning'); ?>');
field.value = field.value.replace(/[^0-9-'.'-',']/g,"");
}
}
</script>

<script language="JavaScript" type="text/javascript">
function isNumber2(field) {
var re = /^[0-9]*$/;
if (!re.test(field.value)) {
alert('<?php echo translate('numericwarning2'); ?>');
field.value = field.value.replace(/[^0-9]/g,"");
}
}
</script>

<div id='postpath'>
		<a title="<?php echo translate('gotofrontpage'); ?>" href="index.php"><?php echo translate('home'); ?></a>
        &gt; <a href="index.php?action=blogs" title='<?php echo translate('showallblogs'); ?>'><?php echo translate('blog'); ?></a> 
		&gt; <a href="index.php?action=profile&amp;id=<?php echo $USER->getId(); ?>"><?php echo ucf($USER->getFirstname()) . " " . ucf($USER->getLastname()); ?></a>
        &gt; <a href="index.php?action=profile&amp;sub=newt" title='<?php echo translate('addnewtraining'); ?>'><?php echo translate('addnewtraining'); ?></a> 
</div>
<br />
<h2><?php echo translate('addnewtraining'); ?></h2>
<br />
<p><?php echo translate('helptexttraining'); ?></p>
    
<form action="index.php?action=profile&amp;sub=newt" method="post" name="new_ex_form" id="new_ex_form">
	<br />
	<b><?php echo translate('title'); ?>:</b> <input type="text" id="title" name="title" size="50" value="<?php echo $blog['title']; ?>"/> 
	<?php 
	if(isset($missing['title'])) 
	{
		echo "<span class=\"error\"><-- " . translate($missing['title']) . "</span>";
	}
	?>
    <b><?php // echo translate('date'); ?></b>
<select class="select" id="day" name="day">
        <?php
        for($i=1; $i<=31; $i++)
        {
            if($i == $blog['day'])
            {
                echo "<option value=\"" . $i . "\" selected=\"selected\">" . $i . "</option>\n";
            }
            else
            {
                echo "<option value=\"" . $i . "\">" . $i . "</option>\n";
            }
        }
        ?>
    </select>
    <select class="select" id="month" name="month">
        <?php
        foreach($MONTHS as $k => $v)
        {
            if(($k+1) == $blog['month'])
            {
                echo "<option value=\"" . ($k+1) . "\" selected=\"selected\">" . ucfirst(translate($v)) . "</option>\n";
            }
            else
            {
                echo "<option value=\"" . ($k+1) . "\">" . ucfirst(translate($v)) . "</option>\n";
            }
        }
        ?>
    </select>
    <select class="select" id="year" name="year">
        <?php
        for($i=date('Y', $time_now); $i>=(date('Y', $time_now) - 11); $i--)
        {
            if($i == $blog['year'])
            {
                echo "<option value=\"" . $i . "\" selected=\"selected\">" . $i . "</option>\n";
            }
            else
            {
                echo "<option value=\"" . $i . "\">" . $i . "</option>\n";
            }
        }
        ?>
    </select> <img src="img/upd.gif" title="<?php echo translate('date'); ?>"/>
    <?php 
	if(isset($missing['day']) or isset($missing['month']) or isset($missing['year']))
	{
		echo "<span class=\"error\"><-- " . translate('missing') . "</span>";
	}
	?>
<br /><br /> 
    	<b><?php echo ucf(translate('type')); ?>:</b>
		<select name="meet">
				<?php
					foreach($array_meet as $key => $val)
					{
						if($blog['meet'] == $key)
						{
							echo "<option value=\"" . $key . "\" selected=\"selected\">" . translate($val) . "</option>\n";
						}
						else
						{
							echo "<option value=\"" . $key . "\">" . translate($val) . "</option>\n";
						}
					}
				?>
		</select>
    	<b><?php echo ucf(translate('category')); ?>:</b>
        <select id="category" name="category">
				<?php
					foreach($array_cat as $val)
					{
							if($blog['category'] == $val['cat_name'])
							{
								echo "<option value=\"" . $val['cat_name'] . "\" selected=\"selected\">" . translate($val['cat_name']) . "</option>\n";
							}
							else
							{
								echo "<option value=\"" . $val['cat_name'] . "\">" . translate($val['cat_name']) . "</option>\n";
								
							}
					}
					echo "<option value=\"uncategorized\">" . translate('nocat') . "</option>\n";
				
				?>
				</select>
                <a href="index.php?action=profile&amp;sub=new_cat"><img src="img/add.png" /><?php echo translate('addnewcat'); ?></a> 
				<?php 
                if(isset($missing['category'])) 
                {
                    echo "<span class=\"error\"><-- " . translate($missing['category']) . "</span>";
                }
                ?>    
         
     <br /><br />
     <b><?php echo translate('exercise'); ?>:</b>
	<select class="selectbox"  id="select_category" name="select_category" onchange="updateOptions(document.new_ex_form.select_category.options[document.new_ex_form.select_category.selectedIndex].value, 'select_exercise1');">
		<option value="" selected="selected"><?php echo translate('select_category'); ?></option>
   
   <?php
 
foreach($EXERCISE_LIST as $key => $value)
{
	$ex_id = $value['id'];
	
	$ex_list = $value['list'];
	$output = translate($value['name']);
	echo "<option value=\"" . $key . "\">".  translate($output) . "</option>\n";
	
/*	
	foreach($ex_list as $k => $v)
	{
		$output = translate($v['name']);
		echo "<option value=\"" . $v['id'] . "\">" . $output . "</option>\n";
	}
*/	
}
	?>
	</select> 
	
	<select id="select_exercise1" name="select_exercise1" class="selectbox"  onchange="javascript:selected_exercise(this.value);" >
	  <option value="" selected="selected"><?php echo translate('selectcategoryfirst'); ?></option>
	</select>
<br />
	<!-- <input type="text" id="select_category2" name="select_category2" onclick="EmptyOnClick('select_category2');" value="<?php echo translate('select_category'); ?>"/>
	-->
	<input style="margin-left:65px;width:315px;" type="text" id="select_exercise2"  name="select_exercise2" onclick="EmptyOnClick('select_exercise2');" value="<?php echo translate('select_an_exercise'); ?>"/>
 	<input type="hidden" id="select_exercise" name="select_exercise" value="0" />
	
	<input type="hidden" id="mod_display" value="" />
<!--	<input type="checkbox" id="mod_checkbox_display" onclick="javascript:change_mode_display(this);" /> 
		<?php echo translate('change_mod_display');?>
-->	
	<a href="javascript:void(0);" id="add_exercise" onclick="add_exercise(); return false;"><img src="img/add.png" /><?php echo translate('addnewexercise'); ?></a>
  <br />
	<?php 
	if(isset($missing['exercise'])) 
	{
		echo "<span class=\"error\">" . translate($missing['exercise']) . "</span>";
	}
	?>
	
	<div id="exercise_list">
		<?php
		
foreach($blog['exercise'] as $key => $value)
{
	$counter = $key + 1;
	echo "<div id=\"exercise[" . $counter . "]\"><br />\n".
	"<span style=\"font-weight:bold; font-size:16px;\">" . ucf(translate(getExercisename($value['id']))) . "</span>\n".
	"<a href=\"javascript:void(0);\" title=\"" . translate('removeexercise') . "\" onclick=\"remove_exercise('" . $counter . "'); return false;\"><img src='img/decline.png' /></a><br />\n".
	"<a href=\"javascript:void(0);\" onclick=\"add_set('" . $counter . "', '" . $value['id'] . "'); return false;\"><div style='float: left; clear: right; padding-right: 5px;'><img src='img/add.png' /></div> " . translate('addnewsettoexercise') . "</a><div style='clear: both;'></div>\n";
	foreach($value['set'] as $k => $v)
	{
		$counter2 = $k + 1;
		echo "<div id=\"set[" . $counter2 . "][" . $counter . "]\">\n".
		"<strong>" . translate('set') . " " . translate('nr') . " " . $counter2 . "</strong><br />\n".
		"<input onkeyup=\"isNumber(this)\" name=\"kgs[" . $value['id'] . "][]\" size=\"4\" type=\"text\" value=\"" . $v['kg'] . "\" /><b>" . translate($w_metric) . " </b>\n".
		"<input onkeyup=\"isNumber2(this)\" name=\"reps[" . $value['id'] . "][]\" size=\"2\" type=\"text\" value=\"" . $v['rep'] . "\" /><b>" . ucf(translate('reps')) . " </b>\n";
		if($rpeactivated == 1)
		{
		echo "<select id=\"rpe_" . $counter2 . "\" name=\"rpe[" . $value['id'] . "][]\">";
		echo "<option value=''></option>\n";
		foreach($array_rpe as $key => $val)
						{
							if($v['rpe'] == $key)
							{
								echo "<option value=\"" . $key . "\" selected=\"selected\">" . $val . "</option>\n";
							}
							else
							{
								echo "<option value=\"" . $key . "\">" . $val . "</option>\n";
							}
						}
				echo "</select> 
				<b>" . translate('RPE') . "</b> <a href='./img/rpe.JPG' rel='prettyPhoto' title='". translate('clicktoopeninanewpage') . "' target='_blank'>[?]</a>";
		}
		if($counter2 != 1)
		{
			echo "<a href=\"javascript:void(0);\" title=\"" . translate('removeset') . "\" onclick=\"remove_set(" . $counter2 . ", " . $counter . "); return false;\"> <img src='img/decline.png' /></a> ";
		}
		echo "<a href=\"javascript:void(0);\" title=\"" . translate("add_video") . "\" onclick=\"add_video(" . $counter2 . "" . $value['id'] . "); return false;\"><span id=\"add_video_button_" . $counter2 . "\"><img src='img/video_add.png' /></span></a> ";
		
		echo "<a href=\"javascript:void(0);\" title=\"" . translate("edit_set") . "\" onclick=\"edit_set(" . $counter2 . "" . $value['id'] . "); return false;\"><span id=\"edit_set_button_" . $counter2 . "\"><img src='img/book_edit.png' /></span><br/></a>";
		
		if($v['url'] != "")
		{
			echo "<div class=\"ex_stats2\" id=\"add_video_" . $counter2 . "" . $value['id'] . "\"><br /><input id=\"url_" . $counter2 . "\" name=\"url[" . $value['id'] . "][]\" size=\"40\" type=\"text\" value=\"" . $v['url'] . "\" /><b>" . ucf(translate('url')) . "</b><br /><br /></div>\n";
		}
		else
		{
			echo "<div class=\"ex_stats\" id=\"add_video_" . $counter2 . "" . $value['id'] . "\"><br /><input id=\"url_" . $counter2 . "\" name=\"url[" . $value['id'] . "][]\" size=\"40\" type=\"text\" value=\"" . $v['url'] . "\" /><b>" . ucf(translate('url')) . "</b><br /><br /></div>\n";
		}
		
		if($v['type'] != "")
		{
			echo "<div class=\"ex_stats2\" id=\"edit_set_" . $counter2 . "" . $value['id'] . "\">
			<br />
			<select id=\"type_" . $counter2 . "\" name=\"type[" . $value['id'] . "][]\">";
			echo "<option value=''>" . translate('selecttype') . "</option>\n";
			foreach($array_set as $key => $val)
						{
							if($v['type'] == $key)
							{
								echo "<option value=\"" . $key . "\" selected=\"selected\">" . translate($val) . "</option>\n";
							}
							else
							{
								echo "<option value=\"" . $key . "\">" . translate($val) . "</option>\n";
							}
						}
			echo "</select>
			<select id=\"type_nr_" . $counter2 . "\" name=\"type_nr[" . $value['id'] . "][]\">";
			echo "<option value=''>" . translate('selecttypenr') . "</option>\n";
			foreach($array_set_nr as $key => $val)
						{
							if($v['type_nr'] == $key)
							{
								echo "<option value=\"" . $key . "\" selected=\"selected\">" . $val . "</option>\n";
							}
							else
							{
								echo "<option value=\"" . $key . "\">" . $val . "</option>\n";
							}
						}
				echo "</select><br /><br /></div>";
		}
		else
		{
			echo "<div class=\"ex_stats\" id=\"edit_set_" . $counter2 . "" . $value['id'] . "\"><br />
		<select id=\"type_" . $counter2 . "\" name=\"type[" . $value['id'] . "][]\">";
		echo "<option value=''>" . translate('selecttype') . "</option>\n";
		foreach($array_set as $key => $val)
					{
						if($v['type'] == $key)
						{
							echo "<option value=\"" . $key . "\" selected=\"selected\">" . translate($val) . "</option>\n";
						}
						else
						{
							echo "<option value=\"" . $key . "\">" . translate($val) . "</option>\n";
						}
					}
		echo "</select>
		<select id=\"type_nr_" . $counter2 . "\" name=\"type_nr[" . $value['id'] . "][]\">";
			echo "<option value=''>" . translate('selecttypenr') . "</option>\n";
			foreach($array_set_nr as $key => $val)
						{
							if($v['type_nr'] == $key)
							{
								echo "<option value=\"" . $key . "\" selected=\"selected\">" . $val . "</option>\n";
							}
							else
							{
								echo "<option value=\"" . $key . "\">" . $val . "</option>\n";
							}
						}
				echo "</select><br /><br /></div>";
		}
		echo "</div>";
	}
	echo "</div>";
}
		?>
	</div>
    
	<br />
	        
	<b><?php echo translate('comment'); ?>:</b>
	<?php 
	if(isset($missing['comment'])) 
	{
		echo "<span class=\"error\"><-- " . translate($missing['comment']) . "</span>";
	}
	?>
	<br />
  <textarea id="comment" name="comment" style="width:100%"><?php echo $blog['comment']; ?></textarea><br />
	<center>
    <table>
    <tr>
    <td align="right"><img src="img/house.png" title="<?php echo translate('place'); ?>"/> 
		<b><?php echo ucf(translate('place')); ?>:</b>
	</td> 
	<td align="left">
		<input type="text" id="place" align="absmiddle" name="place" size="20" value="<?php echo $blog['place']; ?>" />
		<input type="hidden" id="gym_id" name="gym_id" value="<?php echo '';//$blog['gym_id'];?>" />
		&nbsp;&nbsp;
		<a href="index.php?action=gym&sub=list"><?php echo translate('gym_list_view');?></a>
        <?php 
		if(isset($missing['place'])) 
		{
			echo "<span class=\"error\"><-- " . translate($missing['place']) . "</span>";
		}
		?>
        </td>
        </tr>
        
        <tr>
        <td align="right">
        <img src="img/wm_edit.png" title="<?php echo translate('bodyweight'); ?>"/>
        <b><?php echo translate('bodyweight'); ?>:</b></td><td align="left">
		<input onkeyup="isNumber(this)" align="absmiddle" name="bodyweight" type="text" size="4" value="<?php echo $blog['bodyweight']; ?>"/>
		<?php 
		if(isset($missing['bodyweight'])) 
		{
			echo "<span class=\"error\"><-- " . translate($missing['bodyweight']) . "</span>";
		}
		?>
        <b><?php echo ucf(translate($w_metric)); ?></b>
        </td>
        </tr>
        
        <tr>
        <td align="right">
        <img src="img/clock.png" title="<?php echo translate('timespent'); ?>"/>
		<b><?php echo translate('timespent'); ?>:</b></td><td align="left"> 
  <select name="timespent_hours">
			<?php
			for($i = 0; $i<24; $i++)
			{
				if($blog['hour'] == $i)
				{
					echo "<option value=\"" . $i . "\" selected=\"selected\">" . $i . "</option>\n";
				}
				else
				{
					echo "<option value=\"" . $i . "\">" . $i . "</option>\n";
				}
			}
			?>
		</select></b><b>
		<?php echo translate('hours'); ?> 
		<select name="timespent_minutes">
		<?php
			for($i = 0; $i<60; $i+=5)
			{
				if($blog['minute'] == $i)
				{
					echo "<option value=\"" . $i . "\" selected=\"selected\">" . $i . "</option>\n";
				}
				else
				{
					echo "<option value=\"" . $i . "\">" . $i . "</option>\n";
				}
			}
			?>
		</select>
		<?php echo translate('minutes'); ?></b>
		<?php 
		if(isset($missing['hour']) or isset($missing['minute']))
		{
			echo "<span class=\"error\"><-- " . translate('missing') . "</span>";
		}
		?>
	   </td>
        </tr>
        
        <tr>
        <td colspan="2">
		<img src="img/com.png" /> <b><?php echo translate('disable_commenting'); ?></b>
		<?php
		echo "<input type=\"checkbox\" name=\"blog_disablecomments\" ";
		if(isset($disable_comments) && $disable_comments == 1)
		{
			echo "checked=\"checked\"";
		}
		echo " />";
		?>
       <br />
		<div class="set_subtext"><?php echo translate('enableordisablecommentsonyourblog'); ?></div>
        </td>
        </tr>
        </table>
		<br />
		<input id="submit" style="font-weight:bold;" name="blog_submit" type="submit" value=" <?php echo ucf(translate('add')); ?> " /> 
		<input type="reset" style="font-weight:bold;" value=" <?php echo translate('clearallinputs'); ?> " />
	</center>
</form>

<style>
	#sortable { list-style-type: none; margin: 0; padding: 0; width: 100%; }
	#sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px;cursor:pointer; }
	#sortable li span { position: absolute; margin-left: -1.3em; }
</style>

<div id="popup_ui" style="display:none;width:550px;"></div>	 
<div id="sort_ex" style="display:none;width:550px;"></div>	

<script type="text/javascript" charset="utf-8">
 /* $(document).ready(function(){
    $("a[rel^='prettyPhoto']").prettyPhoto();
  });
  */
jQuery(document).ready(function($) { 
//	var cat = $('#select_category2').autocomplete({ 
//  	    serviceUrl:'index2.php?action=user&sub=edit_exercise&task=auto_comp_show_all_cat',
//  	    minChars: 1 , 
// 	        delimiter: /(,|;)\s*/, // regex or character
// 	        maxHeight:300,
//  	    width:200,
//  	    zIndex: 9999,
//  	    deferRequestBy: 0,  
//  	    noCache: true,  
//  	    onSelect: function(value, data){ 
//		    var temp = $("<div>").html(value).text(); 	 
//    	    jQuery("input[name=select_category2]").val(temp) ; 
//    	    sys.cat_id = data;
// 		    choose_ex_kind();
//		    $.post("index2.php?action=user&sub=edit_exercise&task=cat_selected_id&cat_id="+data);
//      	} 
//  	  });
	var ex = $('#select_exercise2').autocomplete({ 
  	    serviceUrl:'index2.php?action=user&sub=edit_exercise&task=show_ex_of_cat',  //
	    minChars: 1 , 
  	    delimiter: /(,|;)\s*/, // regex or character
  	    maxHeight:300,
  	    width:350,
  	    zIndex: 9999,
  	    deferRequestBy: 0,  
  	    noCache: true,  
  	    onSelect: function(value, data){  
		  var temp = $("<div>").html(value).text(); 	 
    	  jQuery("input[name=select_exercise2]").val(temp); 
		  jQuery('#select_exercise').attr('value',data);
		  $('#mod_display').attr('value','');
      	} 
  	  });  
    var place = $('#place').autocomplete({ 
  	    serviceUrl:'index2.php?action=gym&task=auto_comp_show_all_gym',
  	    minChars: 1 , 
  	    delimiter: /(,|;)\s*/, // regex or character
  	    maxHeight:300,
  	    width:200,
  	    zIndex: 9999,
  	    deferRequestBy: 0,  
  	    noCache: true,  
  	    onSelect: function(value, data){ 
		  var temp = $("<div>").html(value).text(); 	
    	  jQuery("input[name=place]").val(temp); 
		  jQuery("input[name=gym_id]").val(data);
      	} 
  	  }); 	  
});

function changed_exrc(){}

function edit_exercise(i,exercise_id){
	$.post("index2.php",{action:'user',sub:'edit_exercise',exercise_id:exercise_id,task:'display_all'}, function(res){
		$('#popup_ui').html(res);
	});
	 
	$("#popup_ui").dialog(
		{ 
			dialogClass: 'dialog',
			width:550,
			buttons: [
			   {
				   text: "OK",
				   click: function(){ 
						$ex_id = $('#ex_ajax').val();
						
						$.post(
							"index2.php",
							{
								action:'user',
								sub:'edit_exercise',
								exercise_id:$ex_id,
								old_ex:exercise_id,
								bring_var:$('#exercise\\['+i+'\\] *').serializeArray(),
								task:'update_ex2',
								i:i
							},
							function(res){
								$('#exercise\\['+i+'\\]').html(res);
								$('#popup_ui').dialog("close"); 
							}
						);
					}
			   }
			] 
		}
	);
}

function sort_exercise(){
	var array_ex_content = [];
	var array_ex_name = [];
	var array_index = [];
	var array_div = [];
	
	var tmp = '';
	var name = '';
	var div = '';
	
	$('#exercise_list input').each(
		function (i,v){
			$(this).attr('value',$(this).val());
		}
	);
	
	$('#exercise_list>div').each(
		function (i,v){
		   var div_id= ''+ v.id;
		   var dd= div_id.replace('[','\\\[');
		   var dd= dd.replace(']','\\\]');
		   $('#'+dd+' select').each(
			   function(ii,vv){
				   var id= vv.id;
				   var value = $('#'+dd+' #'+id).val();
			
				   $('#'+dd+' #'+id+' option:selected').removeAttr('selected');
				   $('#'+dd+' #'+id).removeAttr('selected'); 
				   $('#'+dd+' #'+id+' option[value="'+value+'"]').attr('selected','selected');
			   } 
		   );
		}
	);
	 
	$('#exercise_list>div').each(
		function(i,v){
			tmp = $(this).html();
			name = $(this).find('span').eq(0).text();
			div = $(this).attr('id');
			
			array_ex_content.push(tmp);
			array_ex_name.push(name);
			array_index.push(i);
			array_div.push(div);
		}
	);
	
	var ui= '';
	ui += '<ul id="sortable">';
	for(var i=0; i< array_index.length; i++){
		ui += '<li class="ui-state-default" rel='+array_index[i]+'><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>'+array_ex_name[i]+'</li>';
	}
	ui += "</ul>";
	
	$('#sort_ex').html(ui);
	sort_ex();
	$("#sort_ex").dialog(
		{ 
			dialogClass: 'dialog',
			width:550,
			buttons: [
			   {
				   text: "OK",
				   click: function(){ 
						var array_tid = new Array(); 
						$('#sortable li').each(function(i,o){
							array_tid.push($(this).attr('rel'));
						});
						ui = '';
						for(i=0; i< array_index.length; i++ ){
							ui += "<div id='"+array_div[array_tid[i]]+"'>";
							ui += array_ex_content[array_tid[i]];
							ui += "</div>";
						}
						$('#exercise_list').html(ui);
						$("#sort_ex").dialog("close");
					}
			   }
			] 
		}
	);
}

var sort_ex = function() {
	$( "#sortable" ).sortable();
	$( "#sortable" ).disableSelection();
}
</script>